package com.wwp.tbshop.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.wwp.tbshop.R;
import com.wwp.tbshop.activity.cartactivity.CommitActivity;
import com.wwp.tbshop.activity.cartactivity.DeliverGoodsActivity;
import com.wwp.tbshop.activity.cartactivity.InvoiceActivity;
import com.wwp.tbshop.activity.cartactivity.PayTypeActivity;
import com.wwp.tbshop.model.bean.AddressList;
import com.wwp.tbshop.model.bean.ConfirmBean;
import com.wwp.tbshop.model.bean.OrderSubmitResponseBean;
import com.wwp.tbshop.presenter.ConfirmActivityPresenter;
import com.wwp.tbshop.util.Constant;
import com.wwp.tbshop.util.PriceFormater;
import com.wwp.tbshop.util.SPUtils;
import com.wwp.tbshop.view.custom.MyListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.wwp.tbshop.R.id.iv_next_bill;

/**
 * Created by windows on 2017/6/15.
 */

public class OrderSubmitActivity extends BaseActivity {


    @Bind(R.id.ib_shopcart_back)
    ImageButton mIbShopcartBack;
    @Bind(R.id.user_name)
    TextView mUserName;
    @Bind(R.id.user_phone)
    TextView mUserPhone;
    @Bind(R.id.user_address)
    TextView mUserAddress;
    @Bind(R.id.iv_next_detail)
    ImageView mIvNextDetail;
    @Bind(R.id.edit_address)
    LinearLayout mEditAddress;
    @Bind(R.id.edit_pay)
    TextView mEditPay;
    @Bind(R.id.pay_way)
    TextView mPayWay;
    @Bind(R.id.iv_next_pay)
    ImageView mIvNextPay;
    @Bind(R.id.delivery_time)
    TextView mDeliveryTime;
   /* @Bind(R.id.delivery_way)
    TextView mDeliveryWay;*/
    @Bind(R.id.iv_next_carry)
    ImageView mIvNextCarry;
    @Bind(R.id.delivery)
    LinearLayout mDelivery;
    @Bind(R.id.invoice_head)
    TextView mInvoiceHead;
    @Bind(R.id.invoice_info)
    TextView mInvoiceInfo;
    @Bind(R.id.invoice)
    LinearLayout mInvoice;
    @Bind(iv_next_bill)
    ImageView mIvNextBill;
    @Bind(R.id.rv_product_list)
    MyListView mRvProductList;
    @Bind(R.id.count)
    TextView mCount;
    @Bind(R.id.goods_money)
    TextView mGoodsMoney;
    @Bind(R.id.delivery_money)
    TextView mDeliveryMoney;
    @Bind(R.id.total_money)
    TextView mTotalMoney;
    @Bind(R.id.btn_commit)
    Button mBtnCommit;
    @Bind(R.id.scrollView)
    ScrollView mScrollView;

    private Context mContext;
    private int mDeliveryType = 0;
    private String invoiceId = "1";
    private String addressId;
    private String invoiceType;
    private String invoiceTitle;
    private int mPayType = 0;
    // TODO: 2017/6/19 需要处理
    private ConfirmBean confirmInfo;

   /* @Inject
    OrderSubmitOperation mOrderSubmitOperation;*/

    private ConfirmActivityPresenter mConfirmActivityPresenter;
    private String sku;
    private ConfirmAdapter mAdapter;
    private float mCountPrice;

    //DaggerOrderSubmitActivityComponent.builder().orderSumitAvtivityModule(new OrderSumitAvtivityModule(this)).build().in(this);

    @Override
    public int getLayoutId() {
        return R.layout.activity_account_center;
    }

    @Override
    protected void init() {
        super.init();
        processIntent();

        mAdapter = new ConfirmAdapter(this);
        mRvProductList.setAdapter(mAdapter);

    }

    private void processIntent() {
        if (getIntent() != null) {
            sku = getIntent().getStringExtra("sku");
            Log.e("getDataSuccess", "processIntent: " + sku);
            mConfirmActivityPresenter = new ConfirmActivityPresenter(this, sku);
        }
    }

    public void getConfirmInfoSuccess(ConfirmBean confirmInfo) {
        this.confirmInfo = confirmInfo;
        //设置地址信息
        if (confirmInfo.getAddressInfo() != null) {
            ConfirmBean.AddressInfoBean addressInfo = confirmInfo.getAddressInfo();
            setAddressWay(addressInfo);
        }

        //设置支付信息
        if (confirmInfo.getPaymentList() != null) {
            setPayWay();
        }

        //设置送货信息
        if (confirmInfo.getDeliveryList() != null) {
            setDeliveryWay();
        }

        //商品明细信息的设置
        List<ConfirmBean.ProductListBean> productList = confirmInfo.getProductList();
        if (productList != null){
            float totalPrice = 0;
            for (int i = 0; i < productList.size(); i++) {
                totalPrice += (productList.get(i).getProdNum() * productList.get(i).getProduct().getPrice());
            }
            mGoodsMoney.setText(PriceFormater.format(totalPrice));
            mCountPrice = totalPrice + confirmInfo.getCheckoutAddup().getFreight();
            mTotalMoney.setText("实付款:" + PriceFormater.format(mCountPrice));

            mAdapter.setDatas(productList);
        }

        //数量及运费的设置
        if (confirmInfo.getCheckoutAddup() != null) {
            mCount.setText(confirmInfo.getCheckoutAddup().getTotalCount() + "");
            mDeliveryMoney.setText(PriceFormater.format(confirmInfo.getCheckoutAddup().getFreight()));

        }
    }

    //修改地址信息栏
    private void setAddressWay(ConfirmBean.AddressInfoBean addressInfo) {
        addressId = addressInfo.getId() + "";
        mUserName.setText(addressInfo.getName());
        StringBuffer sb = new StringBuffer();
        sb.append(addressInfo.getProvince());
        sb.append(addressInfo.getCity());
        sb.append(addressInfo.getAddressArea()).append(addressInfo.getAddressDetail());
        mUserAddress.setText(sb.toString());
        mUserPhone.setText(addressInfo.getPhoneNumber());
    }

    //设置支付方式
    private void setPayWay() {
        ConfirmBean.PaymentListBean paymentListBean = confirmInfo.getPaymentList().get(mPayType);
        mPayWay.setText(paymentListBean.getDes());
    }

    //修改送货信息
    private void setDeliveryWay() {
        ConfirmBean.DeliveryListBean deliveryListBean = confirmInfo.getDeliveryList().get(mDeliveryType);
        mDeliveryTime.setText(deliveryListBean.getDes());
    }


    @OnClick({R.id.ib_shopcart_back, R.id.btn_commit, R.id.iv_next_detail, R.id.iv_next_pay, R.id.iv_next_carry, R.id.iv_next_bill})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_shopcart_back:
                //返回按钮
                finish();
                break;
            case R.id.btn_commit:
                //提交订单
                submit();
                break;
            case R.id.iv_next_detail:
                //填写地址
                Intent intentAddress = new Intent(this, AddOrEditAddressActivity.class);
                startActivityForResult(intentAddress, Constant.ADDRESS_REQUEST_CODE);
                break;
            case R.id.iv_next_pay:
                //选择支付方式
                Intent intentPay = new Intent(this, PayTypeActivity.class);
                startActivityForResult(intentPay, Constant.PAY_REQUEST_CODE);
                break;
            case R.id.iv_next_carry:
                //选择配送方式
                Intent intentDelivery = new Intent(this, DeliverGoodsActivity.class);
                startActivityForResult(intentDelivery, Constant.DELIVERY_REQUEST_CODE);
                break;
            case iv_next_bill:
                //填写发票信息
                Intent intentInvoice = new Intent(this, InvoiceActivity.class);
                startActivityForResult(intentInvoice, Constant.INVOICE_REQUEST_CODE);
                break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        switch (requestCode) {
            case Constant.ADDRESS_REQUEST_CODE:
                AddressList.AddressListBean bean = (AddressList.AddressListBean) data.getSerializableExtra("addressbean_updata");
                upDateAddress(bean);
                break;
            case Constant.PAY_REQUEST_CODE:
                mPayType = data.getIntExtra("type", 0);
                if (confirmInfo != null) {
                    setPayWay();
                }
                break;
            case Constant.DELIVERY_REQUEST_CODE:
                mDeliveryType = data.getIntExtra("type", 0);
                setDeliveryWay();
                break;
            case Constant.INVOICE_REQUEST_CODE:
                String invoiceHead = data.getStringExtra("invoiceHead");
                String invoiceInfo = data.getStringExtra("invoiceInfo");
                invoiceId = data.getStringExtra("invoiceId");
                mInvoiceHead.setText(invoiceHead);
                mInvoiceInfo.setText(invoiceInfo);
                break;
        }

    }

    private void upDateAddress(AddressList.AddressListBean bean) {
        addressId = bean.getId() + "";
        mUserName.setText(bean.getName());
        mUserPhone.setText(bean.getPhoneNumber());
        StringBuffer sb = new StringBuffer();
        sb.append(bean.getProvince())
                .append(bean.getCity())
                .append(bean.getAddressArea())
                .append(bean.getAddressDetail());
        mUserAddress.setText(sb.toString());
    }

    private void submit() {

        if (addressId == null) {
            Toast.makeText(this, "请添加地址", Toast.LENGTH_SHORT).show();
            return;
        }

        // TODO: 2017/6/20 跳转到支付
        Intent intent = new Intent(this, CommitActivity.class);

/*        sku	商品ID:数量:属性ID|商品ID:数量:属性ID	1:3:1,2,3,4|2:2:2,3
        addressId	地址簿ID	139
        paymentType	支付方式	1
        deliveryType	送货时间	1
        invoiceType	发票类型	1=>个人 2=>单位
        invoiceTitle	发票抬头	传智慧播客教育科技有限公司
        invoiceContent	发票内容	1*/

        setInvoice();//判断一下发票类型


        Bundle bundle = new Bundle();
        bundle.putString("sku", sku);
        bundle.putString("addressId", addressId);
        bundle.putString("paymentType", mPayType + 1 + "");
        bundle.putString("deliveryType", mDeliveryType + 1 + "");
        bundle.putString("invoiceType", invoiceType);
        bundle.putString("invoiceTitle", invoiceTitle.replace("发票抬头:", ""));
        bundle.putString("invoiceContent", invoiceId);
        bundle.putFloat("totalPriced", mCountPrice);
        intent.putExtras(bundle);
        startActivity(intent);


    }

    private void setInvoice() {
        String title = mInvoiceHead.getText().toString().trim();
        if (title.equals("个人")) {
            invoiceType = "1";
            invoiceTitle = "个人";
        } else {
            invoiceType = "2";
            invoiceTitle = title;
        }
    }

    //订单提交后，服务器返回数据的处理
    public void processOrderSubmitResponse(OrderSubmitResponseBean orderSubmitResponseBean) {
        if (orderSubmitResponseBean.response.equals("error")) {
            Toast.makeText(this, orderSubmitResponseBean.error, Toast.LENGTH_LONG).show();
        } else {
            OrderSubmitResponseBean.OrderInfoBean orderInfo = orderSubmitResponseBean.orderInfo;

            Intent intent = new Intent(this, CommitActivity.class);
            /*
                public String orderId;
                public int paymentType;
                public int price;
             */
            intent.putExtra("orderId", orderInfo.orderId);
            intent.putExtra("paymentType", orderInfo.paymentType);
            intent.putExtra("price", orderInfo.price);
            startActivity(intent);

        }

    }

    // TODO: 2017/6/20  获取要提交服务器的订单数据
    public Map<String, String> getOrderParams() {
      
        Map<String, String> map = new HashMap<>();
        map.put("sku", "1:3:1,2,3,4|2:2:2,3");
        map.put("addressId", "139");
        map.put("paymentType", "1");
        map.put("deliveryType", "1");
        map.put("invoiceType", "1");
        map.put("invoiceTitle", "传智慧播客教育科技有限公司");
        map.put("invoiceContent", "1");

        return map;
    }

    // TODO: 2017/6/18 从缓存中获取userId
    public int getUserId() {
        return (Integer.parseInt(SPUtils.getString(mContext, SPUtils.USERID, "0")));
    }



    public class ConfirmAdapter extends BaseAdapter {
        private Context context;
        public List<ConfirmBean.ProductListBean> mDatas = new ArrayList<>();

        public void setDatas(List<ConfirmBean.ProductListBean> list) {
            mDatas.addAll(list);
            notifyDataSetChanged();
        }


        public ConfirmAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            if (mDatas.size() != 0) {
                return mDatas.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if (mDatas != null) {
                return mDatas.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ConfirmHolder confirmHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_confirm, parent, false);
                confirmHolder = new ConfirmHolder(convertView);
                convertView.setTag(confirmHolder);
            } else {
                confirmHolder = (ConfirmHolder) convertView.getTag();
            }
            confirmHolder.setData(mDatas.get(position));
            return convertView;
        }


        class ConfirmHolder {
            @Bind(R.id.icon)
            ImageView mIcon;
            @Bind(R.id.name)
            TextView mName;
            @Bind(R.id.attribute)
            TextView mAttribute;
            @Bind(R.id.money)
            TextView mMoney;
            @Bind(R.id.count)
            TextView mCount;

            ConfirmHolder(View view) {
                ButterKnife.bind(this, view);
            }

            public void setData(ConfirmBean.ProductListBean bean) {
                mCount.setText("x" + bean.getProdNum());
                ConfirmBean.ProductListBean.ProductBean product = bean.getProduct();
                mName.setText(product.getName());
                mMoney.setText(PriceFormater.format(product.getPrice()));
                StringBuffer sb = new StringBuffer();
                List<ConfirmBean.ProductListBean.ProductBean.ProductPropertyBean> productProperty = product.getProductProperty();
                for (int i = 0; i < productProperty.size(); i++) {
                    sb.append(productProperty.get(i).getK()).append(":").append(productProperty.get(i).getV()).append(" ");
                }
                mAttribute.setText(sb.toString());
                Picasso.with(context).load(Constant.HOST + product.getPic()).into(mIcon);
            }
        }
    }
}